package com.xxx.mch.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xxx.mch.dao.PermMapper;
import com.xxx.mch.domain.dto.UserData;
import com.xxx.mch.domain.po.Perm;
import com.xxx.mch.exception.BusinessException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class MchInterepter implements HandlerInterceptor
{
    public static final ThreadLocal<UserData> UID = new ThreadLocal<>();

    public static String globalToken = null;
    @Autowired
    private PermMapper permMapper;

    @Value("${hive.auth-url}")
    private String authUrl;

    @Value("${hive.site-code}")
    private String siteCode;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){

        // 如果是OPTIONS请求则结束
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }
        String token = request.getHeader("sobeyhive-http-token");
        if (StringUtils.isEmpty(token))
        {
            throw new BusinessException("请求头没有sobeyhive-http-token信息");
        }
        globalToken = token;
        String method = request.getMethod();
        String uri = request.getRequestURI();
        try
        {
            RestTemplate restTemplate = new RestTemplate();
            String url = authUrl + "?token=" + token + "&siteCode=" + siteCode;
            ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
            String str = entity.getBody();
       //     log.info("用户权限: {}", str);
            JSONObject obj = JSON.parseObject(str);
            if (obj.getInteger("status") == 200)
            {
                UserData userData = new UserData();
                JSONObject data = obj.getJSONObject("data");
                userData.setUid(data.getString("userCode"));
                JSONArray array = data.getJSONArray("funcPermissions");
                for (int i = 0; i < array.size(); i++)
                {
                    JSONObject jsonObject = array.getJSONObject(i);
                    String permCode = jsonObject.getString("permissionCode");
                    userData.getPermissonCodeList().add(permCode);
                }
                List<Perm> permList = permMapper.selectAll();
                for (Perm perm : permList)
                {
                    Set<String> controllerSet = StringUtils.commaDelimitedListToSet(perm.getPath());
                    if (!userData.getPermissonCodeList().contains(perm.getPermCode())&&(controllerSet.contains(method + ":" + uri) ))
                    {
                        log.info("没有权限：" + uri);
                        throw new BusinessException("没权限访问该功能!");
                    }
                }
                UID.set(userData);
                return  true;
            }
        }
        catch (RuntimeException ex)
        {
            log.error("获取操作权限失败!", ex.getMessage());
        }
        throw new BusinessException("没权限访问该功能!");
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) {
        UID.remove();
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex){
    }
}